package com.vichat.gps.controller;

import com.alibaba.fastjson.JSONObject;
import com.vichat.common.cache.RedisHelper;
import com.vichat.common.util.DateUtil;
import com.vichat.gps.entity.LocationData;
import com.vichat.gps.service.IGpsService;
import com.vichat.user.entity.UserBasic;
import com.vichat.user.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.List;

public class UploadGpsThread implements Runnable {

    private static Logger logger = LoggerFactory.getLogger(UploadGpsThread.class);

    IUserService userService;
    List<LocationData> locations;
    IGpsService gpsService;
    GpsAppCache gpsAppCache;

    public UploadGpsThread(IUserService userService_, IGpsService gpsService_,GpsAppCache gpsAppCache_, List<LocationData> locations_) {
        this.userService = userService_;
        this.locations = locations_;
        this.gpsService = gpsService_;
        this.gpsAppCache = gpsAppCache_;
    }

    @Override
    public void run() {
        try {
            try {
                UserBasic user = null;
                for (LocationData location : locations) {
                    if (user == null) {
                        user = userService.getUserBasicByUid(location.getUid());
                    }
                    location.setPartyId(user.getPartyId());
                    location.setOrgCode(user.getOrgCode());
                    location.setOrgId(user.getOrgId());
                    if(DateUtil.isSameDate(new Date(location.getLocTime()),new Date())) {
                        saveLocationData(location);
                    }else{
                        gpsService.saveLocationData(location);
                    }
                }
            } catch (Exception ee) {
                logger.error(ee.getMessage());
            }
        } catch (Exception e) {
            logger.error("UploadGpsThread>>>>>>" + e.getMessage(), e);
        }
    }


    /**
     * 保存定位信息
     *
     * @param locData
     * @throws Exception
     */
    private void saveLocationData(LocationData locData) throws Exception {
        String jsonStr = RedisHelper.getLocationData(String.valueOf(locData.getUid()));
        if (StringUtils.isNotBlank(jsonStr)) {
            LocationData locationDataFDB = JSONObject.parseObject(jsonStr, LocationData.class);
            if (locationDataFDB.getLocTime().longValue() < locData.getLocTime().longValue()) {
                gpsAppCache.put(locData);
                RedisHelper.setLocationData(String.valueOf(locData.getUid()), JSONObject.toJSONString(locData));
            }
        } else {
            gpsAppCache.put(locData);
            RedisHelper.setLocationData(String.valueOf(locData.getUid()), JSONObject.toJSONString(locData));
        }
    }

}
